package com.yx.shop.web.controller;

import java.io.IOException;
import java.sql.Timestamp;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yx.shop.common.Const;
import com.yx.shop.entitly.*;
import com.yx.shop.service.AddressService;
import com.yx.shop.service.CartService;
import com.yx.shop.service.ItemService;
import com.yx.shop.service.OrderService;
import com.yx.shop.service.impl.AddressServiceImpl;
import com.yx.shop.service.impl.CartServiceImpl;
import com.yx.shop.service.impl.ItemServiceImpl;
import com.yx.shop.service.impl.OrderServiceImpl;
import com.yx.shop.utils.Base64Utils;
import com.yx.shop.utils.RandomUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * @Classname OrderController
 * @Description TODO:
 * @Date 2021/05/09 11:43
 * @Created by yx
 */
@WebServlet("/order")
public class OrderController extends BaseServlet {
    private CartService cartService = new CartServiceImpl();
    private AddressService addressService = new AddressServiceImpl();
    private ItemService itemServices = new ItemServiceImpl();
    private OrderService orderServices = new OrderServiceImpl();

    /**
     * @param request
     * @param response
     * @return java.lang.String
     * @Author:yx
     * @Date 2021/05/09 11:44
     * @Description:获取购物车商品信息
     **/
    public String getInfoForOrder(HttpServletRequest request, HttpServletResponse response) {
        //1.判断是否已登录--->获取登录额session信息
        User user = (User) request.getSession().getAttribute(Const.UserInfo.LOGIN_USER);
        if (user == null) {
            request.getSession().setAttribute("msg", "购物车结算必须先登录");
            //重定向至登录页面--->方便用户登录
            return Const.REDIRECT + "/login.jsp";
        }
        //2.调用业务
        List<Cart> clist = cartService.getCartByUid(user.getUid());
        List<Address> addList = addressService.getAddList(user.getUid());
        //获取购物车数据以及地址数据到订单页面展示处理
        request.setAttribute("cartList", clist);
        request.setAttribute("addList", addList);
        return Const.FORWORD + "/order.jsp";
    }

    /**
     * @Author:yx
     * @return java.lang.String
     * @Date 2021/05/09 14:26
     * @param request
     * @param response
     * @Description:创建订单
     **/
    public String addOrder(HttpServletRequest request, HttpServletResponse response) {
        //1.判断是否已登录--->获取登录额session信息
        User user = (User) request.getSession().getAttribute(Const.UserInfo.LOGIN_USER);
        if (user == null) {
            request.getSession().setAttribute("msg", "提交订单必须先登录");
            //重定向至登录页面--->方便用户登录
            return Const.REDIRECT + "/login.jsp";
        }
        //2.获取参数
        Integer aid = Integer.valueOf(request.getParameter("aid"));
        //3.1创建订单对象
        Orders orders = new Orders();
        //3.2生成订单号--->字符串且唯一
        orders.setOid(RandomUtils.createOrderId());
        orders.setUid(user.getUid());
        orders.setOtime(new Timestamp(System.currentTimeMillis()));
        //4.调用业务
        List<Cart> cartList = cartService.getCartByUid(user.getUid());
        //5.把购物车数据转为item订单项数据
        double sum = 0;
        List<Item> itemList = new ArrayList<>();
        for (Cart cart : cartList) {
            sum += cart.getCcount().doubleValue();
            Item item = new Item(orders.getOid(), cart.getPid(), cart.getCcount().doubleValue(), cart.getCnum());
            //添加至集合
            itemList.add(item);
        }
        orders.setOcount(sum);
        orders.setAid(aid);
        orders.setOstate(Const.OrderInfo.NO_PAY);
        //6.调用业务,保存订单信息
        orderServices.createOrder(orders);
        for (Item item : itemList) {
            //7.保存数据至订单展示项表
            itemServices.addItem(item);
        }
        //8,删除购物车中已提交的商品
        //本购物车暂不提供多个商品,单个结算功能,目前仅支持购物车全部提交--->故为清空购物车
        cartService.clearCart(0,user.getUid());
        return Const.REDIRECT+"/order?method=getOrderList";

    }

    /**
     * @Author:yx
     * @return java.lang.String 
     * @Date 2021/05/09 14:51 
     * @param request
     * @param response
     * @Description:通过uid获取订单信息
     **/
    public String getOrderList(HttpServletRequest request, HttpServletResponse response) {
        //1.判断是否已登录--->获取登录额session信息
        User user = (User) request.getSession().getAttribute(Const.UserInfo.LOGIN_USER);
        if (user == null) {
            request.getSession().setAttribute("msg", "获取订单信息必须先登录");
            //重定向至登录页面--->方便用户登录
            return Const.REDIRECT + "/login.jsp";
        }
        //2.调用业务,获取用户的订单数据
        List<Orders> ordersList = orderServices.getOrderListByUid(user.getUid());
        //3 保存数据转发前端展示数据
        request.setAttribute("orderList",ordersList);
        return Const.FORWORD+"/orderList.jsp";
    }

    /**
     * @Author:yx
     * @return java.lang.String
     * @Date 2021/05/09 16:13
     * @param request
     * @param response
     * @Description:获取订单详情
     **/
    public String getOrderDetail(HttpServletRequest request,HttpServletResponse response){
        //1.判断是否已登录--->获取登录额session信息
        User user = (User) request.getSession().getAttribute(Const.UserInfo.LOGIN_USER);
        if (user == null) {
            request.getSession().setAttribute("msg", "获取订单详情必须先登录");
            //重定向至登录页面--->方便用户登录
            return Const.REDIRECT + "/login.jsp";
        }
        //2.获取参数
        String oid = request.getParameter("oid");
        //3.调用业务,获取用户的订单数据
        Orders order = orderServices.getOrderByOid(oid);
        //3 保存数据转发前端展示数据
        request.setAttribute("order",order);

        return Const.FORWORD+"/orderDetail.jsp";
    }

    /**
     * @Author:yx
     * @return java.lang.String
     * @Date 2021/05/10 10:33
     * @param request
     * @param response
     * @Description:功能暂不实现,在支付回调中已实现该功能
     **/
    public String changeState(HttpServletRequest request,HttpServletResponse response){
        //1.判断是否已登录--->获取登录额session信息
        User user = (User) request.getSession().getAttribute(Const.UserInfo.LOGIN_USER);
        if (user == null) {
            request.getSession().setAttribute("msg", "更改订单状态必须先登录");
            //重定向至登录页面--->方便用户登录
            return Const.REDIRECT + "/login.jsp";
        }
        return null;
    }

    /**
     * @Author:yx
     * @return java.lang.String
     * @Date 2021/05/10 10:33
     * @param request
     * @param response
     * @Description:支付成功回调
     **/
    public String paySuccess(HttpServletRequest request,HttpServletResponse response){
        try {
            //1.获取参数
            String oid = request.getParameter("oid");
            String result = request.getParameter("result");
            ObjectMapper objectMapper = new ObjectMapper();
            WeiXin weiXin = objectMapper.readValue(result, WeiXin.class);
            String result_code = weiXin.getResult().getResult_code();
            if (result_code!=null&&result_code.equals("SUCCESS")){
                //支付成功,修改订单状态为已付款未发货
                //int PAY_NOT_SEND=1;
                orderServices.updateStateByOid(oid,Const.OrderInfo.PAY_NOT_SEND);
                //修改状态后,重新查询订单
                return Const.FORWORD+"/order?method=getOrderList";
            }else {
                //支付失败
                request.getSession().setAttribute("msg","订单:"+oid+"支付失败");
                return Const.REDIRECT+"/message.jsp";
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public String payCheck(HttpServletRequest request,HttpServletResponse response){
        //接收支付返回的参数
        String result = request.getParameter("result");
        ObjectMapper objectMapper = new ObjectMapper();
        WeiXin weiXin = null;
        try {
            weiXin = objectMapper.readValue(Base64Utils.decode(result), WeiXin.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //判断付款是否成功
        if (weiXin!=null&&weiXin.getResult().getResult_code().equals("SUCCESS")) {
            //支付成功
            //获取订单号
            String oid = weiXin.getResult().getOut_trade_no();
            System.out.println("payCheck======================>"+oid);
            //通过订单号查询数据
            Orders orders = orderServices.getOrderByOid(oid);
            if (orders.getOcount()==Double.valueOf(weiXin.getResult().getTotal_fee())){
                //订单付款与数据与一致--->修改订单状态
                orderServices.updateStateByOid(oid,Const.OrderInfo.PAY_NOT_SEND);
                //重定向至订单页面--->重新查询订单
                return Const.REDIRECT+"/order?method=getOrderList";
            }else {
                //付款失败
                request.setAttribute("msg","付款失败,请稍后再试");
                return Const.FORWORD+"/message.jsp";
            }
        }else {
            //付款失败
            request.setAttribute("msg","付款失败,余额不足");
            return Const.FORWORD+"/message.jsp";
        }
    }

}
